package com.netty.cn.model.udp.server;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
 
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;

/**
 * 
 * @author wangzonghui
 * @date 2021-11-02 16:32:00
 * @Description udp客户端handler
 */
public class UDPClientHandler extends SimpleChannelInboundHandler<DatagramPacket>{
 
	/**
	 * 接收消息
	 */
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg)
			throws Exception {
		ByteBuf buf = msg.content();
		int len = buf.readableBytes();
		byte[] data = new byte[len];
		buf.readBytes(data);
		String receive = new String(data,"UTF-8");
		System.out.println("client->"+receive);
	}
	
	/**
	 * 发送消息
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("hello,server",Charset.forName("UTF-8")),
				new InetSocketAddress("localhost", 8080)));
	}
 
}
